function hfile = prt_AddCond(hfile, cname, onoffsets, ccolor, pw)
% PRT::AddCond  - add a condition to a PRT file
%
% FORMAT:       [prt = ] prt.AddCond(name, onoffsets [, ccolor [, pw]]);
%
% Input fields:
%
%       name        condition name
%       onoffsets   Ox2 or Ox3 list of on and offsets (and weights)
%       ccolor      condition color
%
% Output fields:
%
%       prt         altered PRT object
%
% Note: all input arguments are optional. if none is given, an
%       empty condition with a 'Condition Nr.' identifier and
%       random color is generated

% Version:  v0.7g
% Build:    9101616
% Date:     Oct-16 2009, 4:18 PM CEST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 1 || ...
    numel(hfile) ~= 1 || ...
   ~isBVQXfile(hfile, 'prt')
    error( ...
        'BVQXfile:BadArgument', ...
        'Invalid call to %s.', ...
        mfilename ...
    );
end
bc = bvqxfile_getcont(hfile.L);
ncon = length(bc.Cond);
if nargin > 1 && ...
    ischar(cname) && ...
   ~isempty(cname)
    cname = cname(:)';
else
    cname = sprintf('Condition %d', ncon + 1);
end
pweights = [];
if nargin > 2 && ...
    isa(onoffsets, 'double') && ...
    length(size(onoffsets)) == 2 && ...
    any((2:3) == size(onoffsets, 2)) && ...
    all(all(onoffsets(:, 1:2) >= 0)) && ...
   ~any(isinf(onoffsets(:)) | isnan(onoffsets(:)))
    if size(onoffsets, 2) > 2
        pweights = onoffsets(:, 3);
    end
    onoffsets = round(onoffsets(:, 1:2));
else
    onoffsets = [];
end
noo = size(onoffsets, 1);
if nargin > 3 && ...
    isa(ccolor, 'double') && ...
    numel(ccolor) == 3 && ...
   ~any(isinf(ccolor) | isnan(ccolor) | ccolor < 0 | ccolor >= 256)
    ccolor = floor(ccolor(:)');
else
    ccolor = floor(255.99 * rand(1,3));
end
if nargin > 4 && ...
    isa(pw, 'double') && ...
    numel(pw) == noo && ...
   ~any(isinf(pw(:)) | isnan(pw(:)))
    pweights = pw(:);
end
if isempty(pweights)
    pweights = ones(noo, 1);
end

% build new condition
newc = struct( ...
    'ConditionName', {{cname}}, ...
    'NrOfOnOffsets', noo, ...
    'OnOffsets',     onoffsets, ...
    'Weights',       pweights, ...
    'Color',         ccolor);

% update object
bc.Cond = [bc.Cond(:)', newc];
bc.NrOfConditions = numel(bc.Cond);
bvqxfile_setcont(hfile.L, bc);
